"""
Author : sunshicheng
DateTime : 2021/6/2.9:22 上午
FileName : leads_grpc.py
Desc: 
"""

import sys
import grpc
import inspect
import time
from locust import task, events, constant, HttpUser
from locust.contrib.fasthttp import FastHttpUser
import leads_services_pb2_grpc
import leads_services_pb2


def stopwatch(func):
    def wrapper(*args, **kwargs):
        previous_frame = inspect.currentframe().f_back
        _, _, task_name, _, _ = inspect.getframeinfo(previous_frame)
        start = time.time()
        result = None
        try:
            result = func(*args, **kwargs)
        except Exception as e:
            total = int((time.time() - start) * 1000)
            events.request_failure.fire(request_type="GRPC",
                                        name="GetCrmTagList",
                                        response_time=total,
                                        response_length=0,
                                        exception=e)
        else:
            total = int((time.time() - start) * 1000)
            events.request_success.fire(request_type="GRPC",
                                        name='GetCrmTagList',
                                        response_time=total,
                                        response_length=0)
        return result

    return wrapper


class GRPCMyLocust(FastHttpUser):
    host = 'http://112.124.46.38:20008'  # 服务端地址和端口号
    wait_time = constant(0)

    def on_start(self):
        pass

    def on_stop(self):
        pass

    @task
    @stopwatch
    def grpc_client_task(self):

        try:  # 服务端地址和端口号
            with grpc.insecure_channel('112.124.46.38:20008') as channel:
                client = leads_services_pb2_grpc.LeadsDaoServerStub(channel)
                # 具体方法 pb2中的方法，request查找对应的方法
                response = client.GetCrmTagList(leads_services_pb2.GetCrmTagListRequest(page=1, limit=1))
                # print(response)
                if 'groupId' in response.data.list:
                    pass
                else:
                    # 错误信息可以自己定义
                    raise Exception
                # 返回值 去pb2 中查找对应的Response
                # list_1 = response.data.list
                # print(list_1)
                # for i in list_1:
                #     print(i.groupId)
                #     print(i.groupName)
                # page_info = response.data.pageInfo
                # print(page_info)
        except (KeyboardInterrupt, SystemExit):
            sys.exit(0)
